import { IVariableItem, IVariableValueType } from './interfaces'
import { mock } from './mock'

// 根据变量类型转换值
export const variableTypeHandlers = {
    number: (value: IVariableValueType) => {
        if (value === undefined) {
            return undefined
        }
        const numbered = Number(value) || parseInt(value?.toString() || '') || 0
        if (isNaN(numbered)) {
            return 0
        }
        return numbered
    },
    boolean: (value: IVariableValueType) => {
        if (value === undefined) {
            return undefined
        }
        if (value === 'false') {
            return false
        } else if (value === 'true') {
            return true
        }
        return !!value
    },
    null: () => null,
    string: (value: IVariableValueType) => {
        if (value === undefined) {
            return undefined
        }
        if (!value) {
            return ''
        }
        if (typeof value !== 'string') {
            return '' + value
        }
        return value
    },
}

// 获取当前expect
export const getCurrentExpect = (apiItem?: IApiItem) => {
    if (!apiItem) {
        return
    }
    const expectId = apiItem?.expectId || 'default'
    const expect =
        expectId === 'default'
            ? apiItem
            : apiItem.expects?.find((e) => e.id === expectId)
    return expect
}

// 获取变量上下文
export const getVarContext = (variables?: IVariableItem[]) => {
    return variables?.reduce(
        (acc, item) => {
            const { name, value, mockRule } = item

            // 如果不使用mock规则或没有mock规则，则不用mock了，直接赋值
            if (!item?.useMock || !mockRule) {
                acc[name] = value
            } else {
                // 否则使用mock值
                acc[name] = mock(mockRule, {
                    noJsonParse: true,
                    noJsonStringify: true,
                })
            }
            return acc
        },
        {} as Record<string, any>,
    )
}

// 默认请求上下文变量，mock时避免未定义变量报错
export const defualtReqContextVars = {
    reqUrl: '',
    reqMethod: '',
    reqHeaders: {},
    reqBody: {},
    reqQuery: {},
    reqParams: {},
    resHeaders: {},
    resBody: {},
}
